package com.version.manager.filter;

import com.alibaba.fastjson.JSONObject;
import com.sun.deploy.net.URLEncoder;
import com.version.manager.constant.BraveConstant;
import com.version.manager.model.Msg;
import com.version.manager.shiro.JWTToken;
import com.version.manager.util.StringPool;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.regex.*;

/**
 * 过滤器,对token进行处理
 */
public class JWTFilter extends BasicHttpAuthenticationFilter  {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * 先检查是否允许匿名访问,然后检查token
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws UnauthorizedException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String[] anonUrl = StringUtils.splitByWholeSeparatorPreserveAllTokens(BraveConstant.ANON_URL, StringPool.COMMA);
        boolean match = false;
        for (String u : anonUrl) {
            String url=httpServletRequest.getRequestURI();
            Pattern pattern = Pattern.compile(u);
            Matcher matcher = pattern.matcher(url);
            if (matcher.find())
                match = true;
        }
        if (match) return true;
        String message="验证失败";
        if (isLoginAttempt(request, response)) {
            try {
                return executeLogin(request, response);

            } catch (Exception e) {
                e.printStackTrace();
                message=e.getMessage();
            }
        }
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
            JSONObject o = new JSONObject();
            o.put("status", "500");
            o.put("message",message);
            writer.write(o.toString());
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return false;
    }

    /**
     * 判断用户是否想要登入。
     * 检测 header 里面是否包含 token 字段
     */
    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        HttpServletRequest req = (HttpServletRequest) request;

        //判断是否允许不登陆就能访问
        String token = req.getHeader("token");
        return token != null;
    }

    /**
     * 执行登陆操作
     */
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String token = httpServletRequest.getHeader("token");
        JWTToken jwtToken = new JWTToken(token);
        // 提交给realm进行登入，如果错误它会抛出异常并被捕获
        getSubject(request, response).login(jwtToken);
        // 如果没有抛出异常则代表登入成功，返回true
        return true;
    }

    /**
     * 对跨域提供支持
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }

    /**
     * 将非法请求跳转到 /unauthorized/**
     */
    private void responseError(ServletResponse response, String message) {
        try {
            //HttpServletResponse httpServletResponse = (HttpServletResponse) response;
            //设置编码，否则中文字符在重定向时会变为空字符串
            //message = URLEncoder.encode(message, "UTF-8");
//            Msg msg= Msg.fail().addMessage("您无权访问");
//            httpServletResponse.getWriter()
//            httpServletResponse.sendRedirect("/unauthorized/" + message);
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter writer = response.getWriter();
            JSONObject o = new JSONObject();
            o.put("status", "500");
            o.put("message",message);
            writer.write(o.toString());
            writer.flush();
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
    }
}
